<?php
/**
 * Created by PhpStorm.
 * User: van404
 * Date: 2017/5/19
 * Time: 22:45
 */

namespace Van\ServiceProvider;

use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Logger as Monolog;
use Psr\Container\ContainerInterface;

class LogServiceProvider
{

    /**
     * @var ContainerInterface
     */
    protected $app;

    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param ContainerInterface $pimple A container instance
     */
    public function register(ContainerInterface $pimple)
    {

        $this->app = $pimple;

        $pimple['logger'] = function () use ($pimple) {

            return $this->createLogger();
        };
    }

    protected function createLogger()
    {
        $this->configureSingleHandler($log = new Monolog($this->channel()));
        return $log;
    }

    /**
     * Get the name of the log "channel".
     *
     * @return string
     */
    protected function channel()
    {
        return $this->app['settings']['env'] ?: 'production';
    }

    /**
     * Configure the Monolog handlers for the application.
     *
     * @param  Monolog $log
     * @return void
     */
    protected function configureSingleHandler(Monolog $log)
    {
        $log->pushHandler(new StreamHandler($this->logPath(), Logger::DEBUG));
    }


    /**
     * Get the log level for the application.
     *
     * @return string
     */
    protected function logLevel()
    {
        return $this->app['settings']['log']['level'] ?: Logger::DEBUG;
    }

    /**
     * Get the maximum number of log files for the application.
     *
     * @return int
     */
    protected function maxFiles()
    {
        if ($this->app['settings']['log']['max_files']) {
            return $this->app['settings']['log']['max_files'] ?: 5;
        }

        return 0;
    }

    protected function logPath()
    {
        return ($this->app['settings']['log']['path'] ?: APP_ROOT . '/logs/') . date('Y-m-d') . '.log';
    }
}